package com.employee.crud.controller;

import com.employee.crud.dao.EmployeeDao;
import com.employee.crud.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/employees")
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao;

    @GetMapping("")
    public ResponseEntity getEmployees(){
        return new ResponseEntity(employeeDao.findAll(), HttpStatus.OK);
    }

    @DeleteMapping("{id}")
    public ResponseEntity  delEmployeeById( @PathVariable Long id){
       employeeDao.deleteById(id);
       return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @PostMapping("")
    public ResponseEntity addEmployee(@RequestBody Employee employee){
        return new ResponseEntity(employeeDao.save(employee),HttpStatus.CREATED);
    }

    @Transactional
    @PutMapping("{id}")
    public ResponseEntity updateEmployee(@RequestBody Employee employee,@PathVariable Long id){
        Employee employee1 = employeeDao.getOne(id);
        employee1.setName(employee.getName());
        employee1.setAge(employee.getAge());
        employee1.setGender(employee.getGender());
        employee1.setSalary(employee.getSalary());
        return new ResponseEntity(employeeDao.save(employee1),HttpStatus.CREATED);

    }
}
